package cn.saltice.idempotence.controller;

import cn.saltice.idempotence.common.ResposeData;
import cn.saltice.idempotence.idem.aspect.Idempotent;
import cn.saltice.idempotence.idem.aspect.IdempotentHandler;
import cn.saltice.idempotence.idem.distributed.DistributedLock;
import cn.saltice.idempotence.idem.enums.ReadWriteTypeEnum;
import cn.saltice.idempotence.idem.exception.IdempotentException;
import cn.saltice.idempotence.idem.request.IdempotentRequest;
import cn.saltice.idempotence.testM.observer.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @program: idempotence
 * @description:
 * @author: Mr.Liu
 * @create: 2020-10-03 21:18
 **/
@RestController
@RequestMapping("/")
public class Test {

    @Autowired
    private DistributedLock distributedLock;
    @Autowired
    private Publisher publisher;

    /**
     * 发布事件测试
     * @param msg
     * @return
     */
    @RequestMapping(value = "pub",method = RequestMethod.GET)
    public ResposeData pub(@RequestParam("msg") String msg){
        publisher.publish(msg);
        return ResposeData.success("欧克");
    }

    @RequestMapping(value = "test",method = RequestMethod.GET)
    public ResposeData test(@RequestParam("key") String key){
        //锁的释放时间一定要考虑好，不然业务处理时间太长了，导致锁被释放了，然后又调用了unLock()方法，就会出现错误
        distributedLock.lock(key,300,(k,ex)->{
            System.out.println("成功："+k);
//            try {
//                Thread.sleep(100);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        },(k,ex)->{
            System.out.println("失败"+k);
        });
        return ResposeData.success("欧克");
    }

    /**
     *  这个key应该用一个分布式id生成器来生成，不能由用户自己提供
     * @param key
     * @return
     */
    @RequestMapping(value = "an",method = RequestMethod.GET)
    @Idempotent(lockName = "test",spelKey = "#key", idempotentHandler = "idempotentHandler",readWriteType = ReadWriteTypeEnum.ORDER)
    public ResposeData an(@RequestParam("key") String key){
        System.out.println("我已经进来了");
        return ResposeData.success("success");
    }

    /**
     * 固定参数格式
     * @param request 请求
     * @param e 异常，需要判断是否为null
     */
    @IdempotentHandler
    public ResposeData idempotentHandler(IdempotentRequest request, IdempotentException e){
        System.out.print(request.getKey() + ": idempotentHandler已经执行过了,");
        if (e != null){
            System.out.println(e.toString());
        }else {
            System.out.println();
        }
        return ResposeData.success("error");
    }
}
